﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Xml.Linq;

namespace eztvReaderLib
{
    public class ezReader
    {
        private Uri url = new Uri("http://showrss.karmorra.info/rss.php?user_id=119959&hd=null&proper=null&namespaces=true&magnets=true");

        public List<ezReader.Item> GetXML()
        {
            XDocument xdocument = XDocument.Parse(new WebClient().DownloadString(this.url), LoadOptions.None);           
            List<ezReader.Item> list = new List<ezReader.Item>();
            foreach (XElement xelement in xdocument.Descendants((XName)"item"))
                list.Add(new ezReader.Item()
                {
                    Date = this.ParseRFC822(xelement.Element((XName)"pubDate").Value),
                    Title = xelement.Element((XName)"title").Value,
                    Link = xelement.Element((XName)"link").Value
                });
            return list;
        }

        private DateTime ParseRFC822(string date)
        {
            date = date.Insert(date.Length - 2, ":");
            DateTime result;
            DateTime.TryParseExact(date, "ddd, dd MMM yyyy HH:mm:ss zzz", (IFormatProvider)CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
            return result;
        }

        private string ParseSize(string Size)
        {
            string[] strArray = new string[9]
              {
                "B",
                "KB",
                "MB",
                "GB",
                "TB",
                "PB",
                "EB",
                "ZB",
                "YB"
              };
            double result;
            if (!double.TryParse(Size, out result))
                return Size;
            int index = 0;
            while (result >= 1024.0)
            {
                result /= 1024.0;
                ++index;
            }
            return string.Format("{0:0.#} {1}", (object)result, (object)strArray[index]);
        }

        public class Item
        {
            public DateTime Date { get; set; }

            public string Title { get; set; }

            public string Link { get; set; }

            public string Size { get; set; }
        }
    }
}
